package com.android.juguotang.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.juguotang.R;
import com.android.juguotang.adapt.CartAdapter;
import com.android.juguotang.app.BaseActivity;
import com.android.juguotang.model.addtocartdata;
import com.android.juguotang.model.ajaxcartCallback;
import com.android.juguotang.model.ajaxcartdata;
import com.android.juguotang.model.getCartCallback;
import com.android.juguotang.model.getcartdata;
import com.android.juguotang.model.group.MainList;
import com.android.juguotang.model.group.MainListCallback;
import com.android.juguotang.model.group.addtocartCallback;
import com.android.juguotang.utils.ConstantsUrl;
import com.android.juguotang.utils.HttpUtils;
import com.android.juguotang.utils.LoginState;
import com.android.juguotang.utils.MyLog;
import com.android.juguotang.utils.ObjectUtils;
import com.android.juguotang.view.MyListView;
import com.google.gson.Gson;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
//购物车页面
public class ProductCartActivity extends BaseActivity implements View.OnClickListener,CartAdapter.RefreshPriceInterface {
    private ProductCartActivity mcontext;
    private boolean networkConnected;
    private LayoutInflater inflater;
    private MyListView listView;
    private NestFullListView lv_hot_product;
    private CheckBox cb_check_all;
    private TextView tv_total_price;
    private TextView tv_delete;
    private TextView tv_go_to_pay;
    private TextView  tv_editCart;
    private TextView  tv_full_price;
    private TextView  tv_difference_price;
    private LinearLayout ll_full_price;
    private CartAdapter adapter;
//    private WebView webview;
    private double totalPrice = 0.00;
    private int totalCount = 0;
    private List<HashMap<String,String>> goodsList;
    private  ArrayList<String> cartislist=new ArrayList<>();
    ArrayList<String> goodsSelectList=new ArrayList<>();
    ArrayList<String> goodsNumList=new ArrayList<>();
    ArrayList<String> goodIdsList=new ArrayList<>();
    ArrayList<String> goodsSpecList=new ArrayList<>();
    ArrayList<String> cartids=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_cart);

        mcontext = ProductCartActivity.this;
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        initDate();
        initView();
    }

    private void initView(){
//        webview=(WebView) findViewById(R.id.webview);
        lv_hot_product=(NestFullListView) findViewById(R.id.lv_hot_product);
        listView = (MyListView) findViewById(R.id.listview);
        cb_check_all = (CheckBox) findViewById(R.id.all_chekbox);
        tv_total_price = (TextView) findViewById(R.id.tv_total_price);
        tv_delete = (TextView) findViewById(R.id.tv_delete);
        tv_go_to_pay = (TextView) findViewById(R.id.tv_go_to_pay);
        tv_editCart= (TextView) findViewById(R.id.tv_editCart);
        tv_full_price= (TextView) findViewById(R.id.tv_full_price);
        tv_difference_price= (TextView) findViewById(R.id.tv_difference_price);
        ll_full_price= (LinearLayout) findViewById(R.id.ll_full_price);
        tv_go_to_pay.setOnClickListener(this);
        tv_delete.setOnClickListener(this);
        cb_check_all.setOnClickListener(this);
        tv_editCart.setOnClickListener(this);
//        webview.loadUrl("http://www.tbfresh.cn/goods/ajax_cart_rand");

    }
    private void initDate(){
        getCart();
        GetDataListData();


    }


    //控制价格展示
    private void priceControl(Map<String, Integer> pitchOnMap){
        cartislist.clear();
        goodsSelectList.clear();
        totalCount = 0;
        totalPrice = 0.00;
        for(int i=0;i<goodsList.size();i++){
            if(pitchOnMap.get(goodsList.get(i).get("id"))==1){
                totalCount=totalCount+Integer.valueOf(goodsList.get(i).get("count"));
                double goodsPrice=Integer.valueOf(goodsList.get(i).get("count"))*Double.valueOf(goodsList.get(i).get("price"));
                totalPrice=totalPrice+goodsPrice;
                cartislist.add(goodsList.get(i).get("id"));
                goodsSelectList.add("1");
            }else{{
                goodsSelectList.add("0");
            }
            }
        }
        tv_total_price.setText("￥ "+totalPrice);
        tv_go_to_pay.setText("付款("+totalCount+")");

        int full_price=Integer.parseInt(tv_full_price.getText().toString());

        if(full_price<totalPrice){
            ll_full_price.setVisibility(View.GONE);
        }else{
            ll_full_price.setVisibility(View.VISIBLE);
            tv_difference_price.setText(""+(full_price-totalPrice));

        }


    }
    //删除操作
    private void checkDelete(Map<String,Integer> map){
        List<HashMap<String,String>> waitDeleteList=new ArrayList<>();
        Map<String,Integer> waitDeleteMap =new HashMap<>();
        for(int i=0;i<goodsList.size();i++){
            if(map.get(goodsList.get(i).get("id"))==1){
                waitDeleteList.add(goodsList.get(i));
                waitDeleteMap.put(goodsList.get(i).get("id"),map.get(goodsList.get(i).get("id")));
            }
        }
        goodsList.removeAll(waitDeleteList);
        map.remove(waitDeleteMap);
        priceControl(map);
        adapter.notifyDataSetChanged();
    }

    //全选或反选
    private void AllTheSelected(){
        Map<String,Integer> map=adapter.getPitchOnMap();
        boolean isCheck=false;
        boolean isUnCheck=false;
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            if(Integer.valueOf(entry.getValue().toString())==1)isCheck=true;
            else isUnCheck=true;
        }
        if(isCheck==true&&isUnCheck==false){//已经全选,做反选
            for(int i=0;i<goodsList.size();i++){
                map.put(goodsList.get(i).get("id"),0);
            }
            cb_check_all.setChecked(false);
        }else if(isCheck==true && isUnCheck==true){//部分选择,做全选
            for(int i=0;i<goodsList.size();i++){
                map.put(goodsList.get(i).get("id"),1);
            }
            cb_check_all.setChecked(true);
        }else if(isCheck==false && isUnCheck==true){//一个没选,做全选
            for(int i=0;i<goodsList.size();i++){
                map.put(goodsList.get(i).get("id"),1);
            }
            cb_check_all.setChecked(true);
        }
        priceControl(map);
        adapter.setPitchOnMap(map);
        adapter.notifyDataSetChanged();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.all_chekbox:
                AllTheSelected();
                break;
            case R.id.tv_go_to_pay:
                if(totalCount<=0){
                    Toast.makeText(mcontext,"请选择要付款的商品~",Toast.LENGTH_SHORT).show();
                    return;
                }
for (int i=0;i<goodsList.size();i++){
    ajaxCart(cartids.get(i),i);
}

                Handler handler=new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ToPay(cartislist,""+totalPrice);
                    }
                },500);

//                Toast.makeText(mcontext,"钱就是另一回事了~",Toast.LENGTH_SHORT).show();
                break;
            case R.id.tv_delete:
                if(totalCount<=0){
                    Toast.makeText(mcontext,"请选择要删除的商品~",Toast.LENGTH_SHORT).show();
                    return;
                }
                checkDelete(adapter.getPitchOnMap());
                break;
                case R.id.tv_editCart:
                    Intent intent=new Intent(mcontext,ProductCartUpdateActivity.class);
                    startActivity(intent);


                    break;
        }
    }

    //获取购物车
    public void getCart(){
        String address = ConstantsUrl.domain + "order/cart";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> header = new HashMap<>();
        MyLog.e("inest","getCart");
        HttpUtils.get(address, null, new getCartCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(getcartdata response, int id) {
                MyLog.e("inest","getCartonResponse");
                ArrayList<getcartdata.cartgoods> cartgoodsList=response.getCart_goods();
//                int count=0;
                if(cartgoodsList!=null&&cartgoodsList.size()>0){
                    for (int i=0;i<cartgoodsList.size();i++){
                     goodIdsList.add(cartgoodsList.get(i).getGoods_id());
                        goodsSpecList.add(cartgoodsList.get(i).getSpec());
                        goodsNumList.add(cartgoodsList.get(i).getQty());
                        cartids.add(cartgoodsList.get(i).getId());
                    }
                }
                goodsList=new ArrayList<>();
                if(cartgoodsList!=null&&cartgoodsList.size()>0){


                for(int i=0;i<cartgoodsList.size();i++){
                    HashMap<String,String> map=new HashMap<>();
                    map.put("id",cartgoodsList.get(i).getId());
                    map.put("goods_id",cartgoodsList.get(i).getGoods_id());
                    map.put("name",cartgoodsList.get(i).getGoods_name());
                    map.put("type",cartgoodsList.get(i).getCost_price());
                    map.put("price",cartgoodsList.get(i).getGoods_price());
                    map.put("count",cartgoodsList.get(i).getQty());
                    map.put("imgsrc",cartgoodsList.get(i).getImg_src());
                    goodsList.add(map);
                }
                }
                adapter=new CartAdapter(mcontext,goodsList);
                adapter.setRefreshPriceInterface(mcontext);
                listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();


            }
        });
    }

    @Override
    public void refreshPrice(Map<String, Integer> pitchOnMap) {
        priceControl(pitchOnMap);
//        for (int i=0;i<adapter.getCount();i++){
//
////                    if((boolean) adapter.getItem(i)){
//            goodsSelectList.add(""+pitchOnMap.get(cartids.get(i)));
//                MyLog.e("inest","pitchOnMap.get(cartids.get(i))="+pitchOnMap.get(cartids.get(i)));
////                    }else{
////                        goodsSelectList.add("0");
////                    }
//            ajaxCart(cartids.get(i),i);
//        }
    }




    public void ajaxCart(String cartid,int i){
//        String address = ConstantsUrl.domain + "order/ajax_cart";
        String address="http://www.tbfresh.cn/api/order/ajax_cart";
        HashMap<String, String> map = new HashMap<>();
//        for(int i=0;i<1;i++) {
//            String cartid=cartids.get(i);
            MyLog.e("inest","goodsSelectList="+goodsSelectList.get(i));
            map.put("is_selected["+cartid+"]", goodsSelectList.get(i));
            map.put("num["+cartid+"]", goodsNumList.get(i));
            map.put("goods_id["+cartid+"]", goodIdsList.get(i));
            map.put("spec["+cartid+"]",goodsSpecList.get(i));
//        }

//        }


        MyLog.e("inest","map="+map.toString());
//        map.put("checkbox","on");
        String getid = LoginState.getInstance().getid(mcontext);
        String getpd = LoginState.getInstance().getpd(mcontext);
        HashMap<String, String> header = new HashMap<>();
        header.put("UID", getid);
        header.put("UPSW", getpd);
        HttpUtils.post(address, header, map, new ajaxcartCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                MyLog.e("inest","Exception="+e.getMessage());
            }

            @Override
            public void onResponse(ajaxcartdata response, int id) {

            }
        });
    }
    private ArrayList<MainList.MainListdata.Mainlistdata> listdata = new ArrayList<>();
    /**
     * 获取大家都在
     * 团列表数据
     */
    private void GetDataListData() {

        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA ;

        HttpUtils.get(address, null, new MainListCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(MainList response, int id) {
                listdata.clear();
                if (response.getData() != null) {
                    MyLog.e("inest","response.getData().getList()="+response.getData().getList().get(0).getName());
                    listdata.addAll(response.getData().getList());
//                    adapter_like.setDatas(listdata);
                    lv_hot_product.setAdapter(new NestFullListViewAdapter<MainList.MainListdata.Mainlistdata>(R.layout.item_group_fragment_main, listdata) {
                        @Override
                        public void onBind(int i, final MainList.MainListdata.Mainlistdata testBean, NestFullViewHolder holder) {
                            holder.setText(R.id.item_grid_fragment_sort_tv, testBean.getName());
                            ObjectUtils.photo(mcontext, testBean.getImg_src(), ((ImageView) holder.getView(R.id.item_grid_fragment_sort_img)));
                            String price1 = testBean.getPrice();
                            SpannableString msp = new SpannableString("￥" + price1);
                            msp.setSpan(new AbsoluteSizeSpan(10, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                            ((TextView) holder.getView(R.id.tv_item_grid_fragment_price)).setText(msp);
                            holder.getView(R.id.iv_item_grid_fragment_add).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    addToCart(testBean.getId());

                                }
                            });
                        }
                    });
                }
            }
        });
    }

    //添加至购物车
    public void addToCart(String id){
        String address = ConstantsUrl.domain + "order/addtocart";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> header = new HashMap<>();

        map.put("qty", "1");
        map.put("id", id);
//        map.put("act", phone);
//        map.put("spec", useraddress);


        HttpUtils.post(address, null, map, new addtocartCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                MyLog.e("inest","response="+e.getMessage());
            }

            @Override
            public void onResponse(addtocartdata response, int id) {
                MyLog.e("inest","response="+response.getData().getRes().getSubtotal() );
                Toast.makeText(mcontext,"添加购物车成功",Toast.LENGTH_LONG).show();
//                getCartCount();
//                getCart();
                initDate();
            }
        });
    }

    private void ToPay(ArrayList<String> cartid,String total) {
        Intent intent = new Intent(this, jgtPayActivity.class);
//        if (goodsItemBeen != null) {
//            showBottomPop(mcontext.getWindow().getDecorView(), check, common_id);
//        } else {
            intent.putStringArrayListExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_ID, cartid);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_TOTAL, total);

//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_NUM, num);
//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_SPEC, spec);
//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_COMMON_ID, common_id);
//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_OPTION, option);
//            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_TYPEID, typeid);
            startActivity(intent);
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initDate();
    }
}
